package com.dong.sqltoy.controller;

import com.dong.sqltoy.model.Order;
import com.dong.sqltoy.model.User;
import com.dong.sqltoy.service.OrderService;
import com.dong.sqltoy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于演示自动填充creator和updater字段功能的控制器
 * 
 * @author dong
 * @Date 2025/9/28
 */
@RestController
@RequestMapping("/api")
public class DemoController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private OrderService orderService;

    /**
     * 创建用户，演示creator和updater字段自动填充
     */
    @PostMapping("/user")
    public Map<String, Object> createUser(@RequestParam String name, @RequestParam Integer age) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            User user = new User();
            user.setId("user_" + System.currentTimeMillis());
            user.setName(name);
            user.setAge(age);
            
            System.out.println("创建用户前 - Creator: " + user.getCreator() + ", Updater: " + user.getUpdater());
            
            Object saveResult = userService.saveUser(user);
            
            // 重新加载用户查看自动填充结果
            User savedUser = new User();
            savedUser.setId(user.getId());
            User loadedUser = userService.loadUser(savedUser);
            
            result.put("success", true);
            result.put("message", "用户创建成功");
            result.put("data", loadedUser);
            result.put("creator", loadedUser != null ? loadedUser.getCreator() : null);
            result.put("updater", loadedUser != null ? loadedUser.getUpdater() : null);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "用户创建失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * 更新用户，演示updater字段自动填充
     */
    @PutMapping("/user/{id}")
    public Map<String, Object> updateUser(@PathVariable String id, @RequestParam String name) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            User queryUser = new User();
            queryUser.setId(id);
            User existingUser = userService.loadUser(queryUser);
            
            if (existingUser == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }
            
            System.out.println("更新用户前 - Creator: " + existingUser.getCreator() + ", Updater: " + existingUser.getUpdater());
            
            existingUser.setName(name);
            Long updateResult = userService.update(existingUser);
            
            // 重新加载用户查看updater字段更新结果
            User updatedUser = userService.loadUser(queryUser);
            
            result.put("success", true);
            result.put("message", "用户更新成功");
            result.put("data", updatedUser);
            result.put("creator", updatedUser != null ? updatedUser.getCreator() : null);
            result.put("updater", updatedUser != null ? updatedUser.getUpdater() : null);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "用户更新失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * 创建订单，演示creator和updater字段自动填充
     */
    @PostMapping("/order")
    public Map<String, Object> createOrder(@RequestParam String userId, @RequestParam BigDecimal amount) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Order order = new Order();
            order.setId("order_" + System.currentTimeMillis());
            order.setUserId(userId);
            order.setAmount(amount);
            order.setCreateTime(LocalDateTime.now());
            
            System.out.println("创建订单前 - Creator: " + order.getCreator() + ", Updater: " + order.getUpdater());
            
            Object saveResult = orderService.saveOrder(order);
            
            // 重新加载订单查看自动填充结果
            Order savedOrder = new Order();
            savedOrder.setId(order.getId());
            Order loadedOrder = orderService.loadOrder(savedOrder);
            
            result.put("success", true);
            result.put("message", "订单创建成功");
            result.put("data", loadedOrder);
            result.put("creator", loadedOrder != null ? loadedOrder.getCreator() : null);
            result.put("updater", loadedOrder != null ? loadedOrder.getUpdater() : null);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "订单创建失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/user/{id}")
    public Map<String, Object> getUser(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            User queryUser = new User();
            queryUser.setId(id);
            User user = userService.loadUser(queryUser);
            
            if (user != null) {
                result.put("success", true);
                result.put("data", user);
            } else {
                result.put("success", false);
                result.put("message", "用户不存在");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        
        return result;
    }
}